/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.nonmember;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.ItemCart;
import model.Product;
import model.ProductService;
import model.SaleOrder;
import model.SaleOrderDetail;
import model.SaleOrderDetailService;
import model.SaleOrderService;
import model.ShoppingCart;
import model.User;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author SONY
 */
public class OrderStep2StrutsAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        List errorMsgs = new LinkedList();
        String Name = "";
        String Address = "";
        String Phone = "";
        try {
            Name = request.getParameter("fullName");
            Address = request.getParameter("address");
            Phone = request.getParameter("phone");
            String PaymentType = request.getParameter("paymenttype");
            String Status = "Mới Đặt";
            if(Name.length() == 0) {
                errorMsgs.add("Họ và Tên không được bỏ trống.");
            }
            if(Address.length() == 0) {
                errorMsgs.add("Địa Chỉ Giao Hàng không được bỏ trống.");
            }
            String phoneExpr = "([0-9]+)";
            if(Phone.length() == 0) {
                errorMsgs.add("Số Điện Thoại Liên Lạc không được bỏ trống.");
            } else if(!Phone.matches(phoneExpr)) {
               errorMsgs.add("Số Điện Thoại Liên Lạc phải là những ký tự số.");
            }
            if(errorMsgs.isEmpty()) {
                //get ShoppingCart object in the session-scope to add ItemCart object to shopping cart
                HttpSession session = request.getSession();
                ShoppingCart shopping_cart = (ShoppingCart) session.getAttribute("shopping_cart");
                double Total = shopping_cart.TotalPrice();
                ArrayList<ItemCart> lstItemCart = shopping_cart.getAllItemCart();
                java.util.Date utilDate = new java.util.Date();
                java.sql.Timestamp OrderDate = new java.sql.Timestamp(utilDate.getTime());
                User user = (User) session.getAttribute("user_member");
                int MemberID = 0;
                if(session.getAttribute("user_member") != null) {
                    MemberID = user.getMemberID();
                }
                SaleOrderService sale_order_service = new SaleOrderService();
                SaleOrder saleorder = sale_order_service.addSaleOrder(MemberID, Name, Address, Phone, OrderDate, Status, Total, PaymentType);
                if(saleorder != null) {
                    int saleorderid = saleorder.getSaleOrderID();
                    for(int i = 0; i < lstItemCart.size(); i++) {
                        String ProductID = lstItemCart.get(i).getProductID();
                        int OrderQty = lstItemCart.get(i).getQuantity();
                        double LineTotal = lstItemCart.get(i).getTotalLine();
                        SaleOrderDetailService sale_order_detail_service = new SaleOrderDetailService();
                        SaleOrderDetail saleorderdetail = sale_order_detail_service.addSaleOrderDetail(saleorderid, ProductID, OrderQty, LineTotal);
                        if(saleorderdetail != null) {
                            //cập nhật lại sl hàng tồn kho khi đặt hàng thành công
                            ProductService product_service = new ProductService();
                            Product product = product_service.getProductDetails_byPID(ProductID);
                            int QOH = product.getQOH();
                            int new_QOH = QOH - OrderQty;
                            if(product_service.changeQOH(ProductID, new_QOH)) {
                                System.out.println("inserted successful!");
                            }
                        }
                    }
                    shopping_cart.makeEmpty();
                    return mapping.findForward(SUCCESS);
                }                
            }            
            
        } catch (Exception e) {
            System.err.println(e);
        }
        request.setAttribute("errorMsgs", errorMsgs);
        request.setAttribute("Name", Name);
        request.setAttribute("Address", Address);
        request.setAttribute("Phone", Phone);
        return mapping.findForward("error");
    }
}
